// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'babel-polyfill'
import Vue from 'vue'
import vuet from '../vuet'
import VueRouter from 'vue-router'
import store from '../vuex'
import * as routers from '../routers'
import * as filters from '../filters'
import * as request from '../request'
import * as utils from '../utils'
import 'mint-ui/lib/style.css'
import {Toast, MessageBox, Indicator} from 'mint-ui'
import config from '../config'
import * as dictionary from '../dictionary'
import native from '../native'
import * as storage from '../storage'
import * as validator from '../validator'
import * as rem from '../rem'
import * as PromiseExtend from '../PromiseExtend'
import FastClick from '../assets/dep/fastclick'

require('../assets/style/global.css')
require('../assets/style/iconfont.css')
require('../assets/style/css.css')

Vue.use(VueRouter)
var components = require('../components')

// 去除手机的300毫秒点击延迟
FastClick.attach(document.body)

rem.init() // 初始化rem单位
PromiseExtend.init() // 初始化Promise的扩展
components.regist(Vue) // 全局注册组件

// 挂载全局参数与方法
Vue.prototype.$request = request
Vue.prototype.$utils = utils
Vue.prototype.$toast = Toast
Vue.prototype.$indicator = Indicator
Vue.prototype.$messageBox = MessageBox
Vue.prototype.$config = config
Vue.prototype.$dictionary = dictionary
Vue.prototype.$native = native
Vue.prototype.$storage = storage
Vue.prototype.$validator = validator
// 实例化Vue的filter
Object.keys(filters).forEach(k => Vue.filter(k, filters[k]))

// 实例化VueRouter
const router = new VueRouter({
  mode: 'history',
  base: '/wap/',
  routes: routers.list,
  scrollBehavior: routers.scrollBehavior
})
// 为保证hbuilder的plus对象在使用时已初始化，在其初始化完成后再启动应用
// document.addEventListener('plusready', function () {
//   new Vue({
//     router,
//     store
//   }).$mount('#app')
// })
// if (config.nativeType == 'pc') {
//   storage.setKey('19607a26ac02059db99b8776d038fc15') // 测试用
// }
storage.setEntryUrl(window.location.href) // 设置当前入口地址

store.registerModule('vux', { // 名字自己定义
  state: {
    animate: 'in'     // 切换动画
  },
  mutations: {
    animateChange(state, payload) {
      state.animate = payload.animate
    }
  }
})

let inviterHandled = false // 处理邀请者相关逻辑， 如给邀请者加积分
let routerArr = [] // 存储路由
let mainPage = ['home', 'cart-list', 'distinguish', 'my', 'classify-buy', 'classify-integral', 'classify-rent']

router.beforeEach(async (to, from, next) => {
  routerArr.push(to.path) // 每次push
  let inviter = to.query.inviter
  if (!inviterHandled) {
    if (inviter) {
      inviterHandled = true
      request.integralAddByShareFriend(inviter).then((data) => {
        console.log('分享者获得积分', data)
      }).catch(e => {
        console.log('分享获得积分错误', e)
      })
    }
  }
  if (to.meta.login) { // 需要先登录才能访问的页面
    let key = storage.getKey()
    console.log('key', key)
    // 需要的登录后才能访问
    if (!key || key == '' || key == 'null') {
      key = await request.getKey()
      if (key) {
        storage.setKey(key)
        next()
        return
      } else {
        let deviceType = utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          let toUrl = config.website + '/wap' + to.fullPath
          native.weixinLogin(toUrl) // 微信授权后才能取到key
          return
        } else {
          routerArr.pop()// 删除最后一个
          next({name: 'login-password'})
          return
        }
      }
    } else {
      if (!storage.getMemberInfo()) {
        let memberInfo = await request.getMemberInfo()
        storage.setMemberInfo(memberInfo)
      }
    }
  }
  if (to.meta.auth) { // 需要完善资料后才能访问的页面
    let auth = storage.getAuthed()
    if (!auth || auth == '' || auth == 'null') {
      let authStatus = await request.getAuth()
      if (authStatus != '1') { // 未完善过
        let query = to.query
        query.to = to.name
        routerArr.pop()// 删除最后一个
        next({name: 'member-register', query: query, params: to.params})
        return
      } else {
        storage.setAuthed(true)
        next()
        return
      }
    }
  }
  next()
  if (routerArr[routerArr.length - 3] === to.path) { // 后退
    store.commit('animateChange', {
      animate: 'out' // 变成后退动画
    })
    routerArr.splice(routerArr.length - 2, 2)
  } else {
    store.commit('animateChange', {
      animate: 'in' // 变成前进动画
    })
  }
  if (mainPage.indexOf(to.name) != -1 && mainPage.indexOf(from.name) != -1) {
    store.commit('animateChange', {
      animate: '' // 变成前进动画
    })
  }
})
router.afterEach((to, from) => {
  let title = to.query.title || to.meta.title || '遇花园'
  utils.setWechatTitle(title)
  utils.removeBodyFix() // 去除body的滚动固定
  // setTimeout(() => {
  //   native.weixinShare(window.location.href) // 每个页面需要重新进行微信配置
  // }, 200)
})

// 全局注入混合
Vue.mixin({
  mounted() {
    window.scrollTo(1, 1) // 移动1px，解决浏览器后退时，需要滚动下页面才会渲染页面的bug
  }
})

new Vue({
  router,
  vuet,
  store
}).$mount('#app')
